#!usr/bin/env python
# -*- coding: utf-8 -*-
from datetime import datetime

from werkzeug import security

from ._base import BaseModel, db
from fx.constants.user import UserRoles


class AdminUser(BaseModel):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    mobile_num = db.Column(db.String(20), unique=True, index=True, nullable=False)
    username = db.Column(db.String(50), nullable=True)
    password = db.Column(db.String(100), nullable=False)
    company = db.Column(db.String(100))
    name = db.Column(db.String(100))
    role = db.Column(db.Integer, nullable=False)
    created = db.Column(db.DateTime, default=datetime.now)
    token = db.Column(db.String(20))
    is_active = db.Column(db.Boolean, default=True)

    dict_default_columns = ['id', 'mobile_num', 'username', 'company', 'name', 'role', 'created', 'is_active', 'token']

    def __init__(self, **kwargs):
        self.token = self.create_token(16)
        if 'password' in kwargs:
            raw = kwargs.pop('password')
            self.password = self.create_password(raw)

        super(AdminUser, self).__init__(**kwargs)

    @property
    def is_admin(self):
        return self.role == UserRoles.ADMIN.value

    @property
    def is_staff(self):
        return self.role == UserRoles.STAFF.value

    def check_password(self, raw):
        pass_check = '%s%s' % (raw, db.app.config['PASSWORD_SECRET'])
        return security.check_password_hash(self.password, pass_check)

    def create_password(self, raw):
        pass_check = '%s%s' % (raw, db.app.config['PASSWORD_SECRET'])
        return security.generate_password_hash(pass_check)

    def create_token(self, length=16):
        return security.gen_salt(length)
